package org.example.fronted.utils.utils;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

public class XMLUtilTest {

    //Map-生成请求的xml
    public static String createXML(TreeMap<String,Object> map) throws IOException {
        SortedMap<String,Object> sort=new TreeMap<String,Object>(map);
        Set<String> keySet = sort.keySet();
        StringBuilder sb = new StringBuilder("<xml>");
        for (Object key : keySet) {
            sb.append(String.format("<%s>%s</%s>", key, map.get(key), key));
        }
        sb.append("</xml>");
        return sb.toString();
    }



    //解析xml
    public static String getElementValue(InputStream is, String key){
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(is);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = document.getRootElement();
        List<Element> elementList = root.elements();

        for (Element element : elementList) {
            System.out.println(element.getName()+ ": "+ element.getStringValue());
            if (key.equals(element.getName())){
                return element.getStringValue();
            }
        }
        return null;
    }

    public static HttpResponse sendXmlDataByPost(String url, String xmlData) throws IOException {

        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(xmlData);
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type","text/xml;charset=UTF-8");
        HttpResponse response = httpClient.execute(httpPost);
        return response;
    }
}
